package jp.sinya.session;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //验证码处理
        String sessionVerifyCode = (String) req.getSession().getAttribute("verify_code");
        String paramCode = req.getParameter("verify_code");
        if (null != sessionVerifyCode && null != paramCode) {
            if (!sessionVerifyCode.equalsIgnoreCase(paramCode)) {
                req.setAttribute("error", "验证码错误");
                req.getRequestDispatcher("/jsp/verify/login.jsp").forward(req, resp);
                return;
            }
        }

        req.setCharacterEncoding("utf-8");
        String userName = req.getParameter("username");
        String password = req.getParameter("password");

        //登陆成功
        if (!"baidu".equalsIgnoreCase(userName)) {

            //把用户名保存到cookie中，发送到客户端浏览器。目的是用户下一次打开浏览器的登陆页面时候，显示用户名在文本框中
            Cookie cookie = new Cookie("cookieUserName", userName);
            cookie.setMaxAge(60 * 10);//保存10分钟
            //如果不设置路径，那么只有设置该Cookie路径及其子路径可以访问.
            cookie.setPath("/");
            resp.addCookie(cookie);

            //保存session
            HttpSession session = req.getSession();
            session.setAttribute("username", userName);
            //重定向到success.jsp(重定向需要添加项目名)
            resp.sendRedirect("/Demo1/jsp/session/success.jsp");

            //登陆失败
        } else {
            req.setAttribute("error", "用户名或密码错误");
            //转发/包含 不需要项目名
            RequestDispatcher dispatcher = req.getRequestDispatcher("/jsp/session/login.jsp");
            dispatcher.forward(req, resp);
        }
    }
}
